package com.roger.homecenterscreen

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.roger.homecenterscreen.ui.components.AnalogClock
import com.roger.homecenterscreen.ui.components.CustomContentDisplay
import com.roger.homecenterscreen.ui.components.DateTimeDisplay
import com.roger.homecenterscreen.ui.components.LocationPermissionHandler
import com.roger.homecenterscreen.ui.components.WeatherDisplay
import com.roger.homecenterscreen.ui.components.MIUIPermissionDialog
import com.roger.homecenterscreen.ui.components.RTModeErrorExplanation
import com.roger.homecenterscreen.ui.components.EInkDisplayAdapter
import com.roger.homecenterscreen.ui.components.FullScreenWrapper
import com.roger.homecenterscreen.ui.components.TimeSyncStatusDisplay
import com.roger.homecenterscreen.ui.components.NetworkStatusBar
import com.roger.homecenterscreen.ui.components.VoiceIndicator
import com.roger.homecenterscreen.ui.components.VoiceStatusBottomBar
import com.roger.homecenterscreen.ui.theme.HomeCenterScreenTheme
import com.roger.homecenterscreen.ui.viewmodel.HomeViewModel
import com.roger.homecenterscreen.utils.SystemUtils
import com.roger.homecenterscreen.utils.MIUIPermissionManager
import com.roger.homecenterscreen.utils.NetworkTimeService
import com.roger.homecenterscreen.voice.VoiceManager
import com.roger.homecenterscreen.voice.VoiceState
import com.roger.homecenterscreen.voice.SynthesisState
import android.util.Log
import androidx.core.app.ActivityCompat
import android.Manifest
import android.view.View
import android.view.WindowManager
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import androidx.compose.runtime.remember

class MainActivity : ComponentActivity() {
    
    private lateinit var permissionManager: MIUIPermissionManager
    private lateinit var voiceManager: VoiceManager
    private var showPermissionDialog by mutableStateOf(false)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 最优先：初始化中国时区
        Log.i("MainActivity", "🚀 应用启动，开始初始化中国时区")
        NetworkTimeService.initializeChinaTimeZone()
        
        // 设置全屏显示，适配E-ink屏幕
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        )
        
        // 强制应用全屏并防止系统调整窗口大小
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
        
        // 初始化权限管理器
        permissionManager = SystemUtils.createPermissionManager(this)
        Log.i("MainActivity", "已创建权限管理器: ${permissionManager.javaClass.simpleName}")
        
        // 初始化语音管理器
        voiceManager = VoiceManager.getInstance(this)
        
        // 处理MIUI系统兼容性
        SystemUtils.handleMIUIPermissions(this)
        
        // 请求必要权限
        val hasAllPerm = permissionManager.checkAllPermissions()
        Log.i("MainActivity", "初始权限检查: hasAllPerm=$hasAllPerm")
        if (!hasAllPerm) {
            Log.i("MainActivity", "检测到缺少权限，开始请求 (MIUI=${SystemUtils.isMIUI()})")
            if (SystemUtils.isMIUI()) {
                // MIUI系统显示权限设置指导
                showPermissionDialog = true
            } else {
                // 其他系统直接请求权限
                permissionManager.requestAllPermissions(this)
            }
        } else {
            Log.i("MainActivity", "所有权限已授予")
            
            // 权限已授予，初始化语音功能
            initializeVoiceFeatures()
        }
        
        // 设置全屏显示，隐藏状态栏和导航栏
        enableEdgeToEdge()
        
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.apply {
            hide(WindowInsetsCompat.Type.systemBars())
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
        
        setContent {
            HomeCenterScreenTheme {
                // 直接显示主界面
                HomeCenterScreen()
                
                // MIUI权限设置对话框
                MIUIPermissionDialog(
                    isVisible = showPermissionDialog,
                    onDismiss = { showPermissionDialog = false },
                    onOpenSettings = {
                        showPermissionDialog = false
                        permissionManager.requestAllPermissions(this@MainActivity)
                    },
                    onIgnore = { 
                        showPermissionDialog = false
                    }
                )
            }
        }
    }
    
    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        Log.i("MainActivity", "onRequestPermissionsResult: requestCode=$requestCode, perms=${permissions.joinToString()}, results=${grantResults.joinToString()}")
        val allGranted = permissionManager.handlePermissionResult(
            requestCode, 
            permissions, 
            grantResults, 
            this
        )
        
        if (allGranted) {
            Log.i("MainActivity", "所有权限已授予，应用可以正常运行")
            
            // 权限已授予，初始化语音功能
            initializeVoiceFeatures()
        } else {
            Log.w("MainActivity", "部分权限被拒绝，可能影响某些功能")

            // 即使部分权限被拒绝，只要麦克风权限已授予，也继续启动语音识别
            val micGranted = androidx.core.content.ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.RECORD_AUDIO
            ) == android.content.pm.PackageManager.PERMISSION_GRANTED
            Log.i("MainActivity", "麦克风权限授予状态: $micGranted")
            if (micGranted) {
                Log.i("MainActivity", "检测到麦克风权限已授予，继续初始化语音功能（忽略非关键权限）")
                initializeVoiceFeatures()
            } else {
                Log.w("MainActivity", "麦克风权限未授予，语音识别无法启动")
                Toast.makeText(applicationContext, "需要麦克风权限以进行语音识别", Toast.LENGTH_LONG).show()
                // 尝试只请求麦克风权限，避免非关键权限干扰
                requestMicPermission()
            }
        }
    }

    private fun requestMicPermission() {
        val granted = androidx.core.content.ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == android.content.pm.PackageManager.PERMISSION_GRANTED
        if (!granted) {
            Log.i("MainActivity", "单独请求麦克风权限")
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.RECORD_AUDIO),
                2001
            )
        } else {
            Log.i("MainActivity", "麦克风权限已存在，跳过单独请求")
        }
    }
    
    /**
     * 应用恢复时重新检查权限
     */
    override fun onResume() {
        super.onResume()
        
        // 重新检查权限状态
        if (::permissionManager.isInitialized) {
            permissionManager.handleMIUISpecificIssues()
        }
    }
    
    /**
     * 处理返回键 - 作为桌面应用时不响应返回键
     */
    @Deprecated("Deprecated in Java")
    @Suppress("DEPRECATION")
    override fun onBackPressed() {
        // 作为桌面应用时，不响应返回键
        // 防止用户意外退出桌面
        Log.d("MainActivity", "🏠 桌面应用模式：忽略返回键操作")
        // 不调用super.onBackPressed()来阻止退出
    }
    
    /**
     * 处理Home键 - 确保应用作为桌面时的正确行为
     */
    override fun onUserLeaveHint() {
        super.onUserLeaveHint()
        Log.d("MainActivity", "🏠 用户离开应用（可能按了Home键）")
        
        // 如果是作为桌面应用运行，可以在这里处理特殊逻辑
        // 例如：保存状态、暂停不必要的更新等
    }
    
    /**
     * 当应用成为焦点时
     */
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        
        if (hasFocus) {
            Log.d("MainActivity", "🏠 应用获得焦点 - 家庭中心屏激活")
            // 重新进入全屏模式
            hideSystemUI()
        } else {
            Log.d("MainActivity", "🏠 应用失去焦点")
        }
    }
    
    /**
     * 隐藏系统UI，保持全屏状态
     */
    private fun hideSystemUI() {
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        window.decorView.systemUiVisibility = (
            View.SYSTEM_UI_FLAG_FULLSCREEN
            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        )
        Log.d("MainActivity", "🔒 已重新设置全屏模式")
    }
    
    /**
     * 初始化语音功能
     */
    private fun initializeVoiceFeatures() {
        lifecycleScope.launch {
            try {
                Log.i("MainActivity", "开始初始化语音功能... 打印权限状态报告如下:")
                try {
                    if (::permissionManager.isInitialized) {
                        val report = permissionManager.getPermissionStatusReport()
                        Log.i("MainActivity", "\n$report")
                    }
                } catch (e: Exception) {
                    Log.w("MainActivity", "打印权限状态报告失败", e)
                }
                val success = voiceManager.initialize()
                
                if (success) {
                    Log.i("MainActivity", "语音功能初始化成功，启动连续语音识别（已在VoiceManager中自动触发）")
                    // 连续识别模式已经在VoiceManager.initialize()中自动开始
                } else {
                    val reason = try { voiceManager.getLastInitError() } catch (e: Exception) { null }
                    Log.e("MainActivity", "语音功能初始化失败${if (reason != null) "：$reason" else ""}")
                }
            } catch (e: Exception) {
                Log.e("MainActivity", "语音功能初始化异常", e)
            }
        }
    }
    
    /**
     * 释放资源
     */
    override fun onDestroy() {
        super.onDestroy()
        if (::voiceManager.isInitialized) {
            voiceManager.release()
        }
    }
}

@Composable
fun HomeCenterScreen() {
    val context = LocalContext.current
    val viewModel: HomeViewModel = viewModel { HomeViewModel(context) }
    val contentData by viewModel.contentData.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val error by viewModel.error.collectAsState()
    val weatherData by viewModel.weatherData.collectAsState()
    val calendarData by viewModel.calendarData.collectAsState()
    val hasLocationPermission by viewModel.hasLocationPermission.collectAsState()
    val isGettingLocation by viewModel.isGettingLocation.collectAsState()
    val timeSyncStatus by viewModel.timeSyncStatus.collectAsState()
    
    // 语音功能状态
    val voiceManager = remember { VoiceManager.getInstance(context) }
    val voiceState by voiceManager.voiceState.collectAsState()
    val synthesisState by voiceManager.synthesisState.collectAsState()
    val recognitionResult by voiceManager.recognitionResult.collectAsState()
    val isVoiceInitialized by voiceManager.isVoiceInitialized.collectAsState()
    val lastVoiceprintWav by voiceManager.lastVoiceprintWav.collectAsState()
    
    val snackbarHostState = remember { androidx.compose.material3.SnackbarHostState() }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFF1976D2),
                        Color(0xFF42A5F5),
                        Color(0xFF90CAF9)
                    )
                )
            )
            .padding(16.dp)
    ) {
        // 1. 网络状态栏
        NetworkStatusBar(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 8.dp)
        )
        
        // 位置权限处理
        if (!hasLocationPermission) {
            LocationPermissionHandler(
                modifier = Modifier.weight(1f),
                onPermissionGranted = { viewModel.setLocationPermission(true) },
                onPermissionDenied = { viewModel.setLocationPermission(false) },
                onUseNetworkLocation = { 
                    // 使用网络定位，不需要权限
                    viewModel.getCurrentLocation()
                }
            )
        } else {
            // 2. 时钟时间区 - 增加高度确保信息完整显示
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(380.dp)
                    .padding(bottom = 16.dp),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 左边：圆形时钟
                AnalogClock(
                    modifier = Modifier.weight(1f),
                    size = 370.dp
                )
                
                // 右边：时间日期信息 - 确保有足够空间显示完整信息
                DateTimeDisplay(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxHeight()
                        .padding(vertical = 8.dp),
                    calendarData = calendarData
                )
            }
            
            // 3. 天气和自定义内容区
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(bottom = 10.dp),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 左边：天气信息
                WeatherDisplay(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxHeight(),
                    weatherData = weatherData
                )
                
                // 右边：声纹WAV试听分析
                CustomContentDisplay(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxHeight(),
                    wavFile = lastVoiceprintWav
                )
            }
            
            // 4. 最底部音频交互状态区
            VoiceStatusBottomBar(
                voiceState = voiceState,
                synthesisState = synthesisState,
                recognitionResult = recognitionResult,
                isVoiceInitialized = isVoiceInitialized,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
            )
        }
        
        // 时间同步状态使用 Snackbar 显示，避免系统 Toast Binder 回调问题
        timeSyncStatus?.let { status ->
            LaunchedEffect(status) {
                snackbarHostState.showSnackbar(
                    message = status,
                    withDismissAction = true
                )
            }
        }
        
        // 如果是MIUI系统，显示RTMode错误说明
        if (SystemUtils.isMIUI()) {
            RTModeErrorExplanation()
        }
        androidx.compose.material3.SnackbarHost(hostState = snackbarHostState)
    }

}

@Preview(showBackground = true)
@Composable
fun HomeCenterScreenPreview() {
    HomeCenterScreenTheme {
        HomeCenterScreen()
    }
}
